package com.taoyibao.hongcanting.ui.home.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityPresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.ApiConstant;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.dialog.DialogComment;
import com.taoyibao.hongcanting.dialog.DialogInoutPayPwd;
import com.taoyibao.hongcanting.event.EventFinishActivity;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.AliPayReturnModel;
import com.taoyibao.hongcanting.model.BalanceModel;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.OrderEatTypeMode;
import com.taoyibao.hongcanting.model.OrderInfoModel;
import com.taoyibao.hongcanting.model.ResultStringModel;
import com.taoyibao.hongcanting.model.SanFangBaseModel;
import com.taoyibao.hongcanting.model.UserInfoModel;
import com.taoyibao.hongcanting.ui.home.delegate.PayDelegate;
import com.taoyibao.hongcanting.ui.mine.activity.PaymentResultActivity;
import com.taoyibao.hongcanting.ui.mine.activity.SetPayPwdStepOneActivity;
import com.taoyibao.hongcanting.utils.AliPayUtils;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.DataUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * @author TangAnna
 * @description: 支付页面
 * @date :${DATA} 13:44
 */
public class PayActivity extends BaseActivityPresenter<PayDelegate> implements View.OnClickListener, AliPayUtils.AliPayInterface {
    private String mOrderId;
    private DialogInoutPayPwd mPayPwd;
    private DialogComment mDialogComment;
    private AliPayUtils mAliPayUtils;
    private String memberId;
    private String mDeskId;

    @Override
    protected Class<PayDelegate> getDelegateClass() {
        return PayDelegate.class;
    }

    /**
     * @param context
     * @param orderId  订单ID
     * @param memberId 订单所属人的memberID
     */
    public static void open(Context context, String orderId, String memberId) {
        Intent intent = new Intent(context, PayActivity.class);
        intent.putExtra(CodeConstant.ORDER_ID, orderId);
        intent.putExtra(CodeConstant.MEMBER_ID, memberId);
        context.startActivity(intent);
    }

    /**
     * 从餐厅模块进入使用
     *
     * @param context
     * @param orderId
     * @param memberId
     * @param deskId   桌位号
     */
    public static void open(Context context, String orderId, String memberId, String deskId) {
        Intent intent = new Intent(context, PayActivity.class);
        intent.putExtra(CodeConstant.ORDER_ID, orderId);
        intent.putExtra(CodeConstant.DESK_ID, deskId);
        intent.putExtra(CodeConstant.MEMBER_ID, memberId);
        context.startActivity(intent);
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        mOrderId = getIntent().getStringExtra(CodeConstant.ORDER_ID);
        memberId = getIntent().getStringExtra(CodeConstant.MEMBER_ID);
        viewDelegate.get(R.id.btn_pay_confirm).setOnClickListener(this);
        getUserBalance();

        //如果是从餐厅地图模块进入的不需要判断就餐方式，直接是堂食
        if (!TextUtils.isEmpty(getIntent().getStringExtra(CodeConstant.DESK_ID))) {
            mDeskId = getIntent().getStringExtra(CodeConstant.DESK_ID);
            getFoodOrderInfo();
            return;
        }
        getOrderEatType();

    }

    /**
     * 获取用户余额
     */
    public void getUserBalance() {
        JsonApiWrapper.getApiService().userBalance(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<BalanceModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<BalanceModel>>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<BalanceModel>> balanceModel) {
                        if (balanceModel.code == NetCode.HTTP_200) {
                            viewDelegate.setBalanceUI(balanceModel.data);
                        } else {
                            super.onNext(balanceModel);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    /**
     * 获取订单就餐方式
     */
    private void getOrderEatType() {
        JsonApiWrapper.getApiService().orderEatType(SpUtils.getToken(), mOrderId, CodeConstant.SELECT_ORDERID_EAT_TYPE, null, null)
                .compose(new DefaultTransformer<CompanyBaseModel<List<OrderEatTypeMode>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<OrderEatTypeMode>>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<OrderEatTypeMode>> companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200 && companyBaseModel.data != null && companyBaseModel.data.size() > 0) {
                            OrderEatTypeMode orderEatTypeMode = companyBaseModel.data.get(0);
                            if (orderEatTypeMode.eatType == CodeConstant.EAT_TYPE_TANGSHI) {//堂食
                                mDeskId = companyBaseModel.data.get(0).deskId;
                                getFoodOrderInfo();
                            } else if (orderEatTypeMode.eatType == CodeConstant.EAT_TYPE_WAIDAI) {//外带
                                getTakeOutOrderInfo();
                            }
                        }
                    }
                });
    }

    /**
     * 获取堂食订单详情
     */
    public void getFoodOrderInfo() {

        JsonApiWrapper.getApiService().getDeskOrderInfo(ApiConstant.MASTER_ID, DataUtils.getKey(), ApiConstant.BRANCH_ID, mDeskId)
                .compose(new DefaultTransformer<SanFangBaseModel<OrderInfoModel>>())
                .subscribe(new ProgressSubscriber<SanFangBaseModel<OrderInfoModel>>(this, true) {
                    @Override
                    public void onNext(SanFangBaseModel<OrderInfoModel> orderInfoModel) {
                        if (orderInfoModel.Code == NetCode.HTTP_200 && orderInfoModel.Data != null) {
                            viewDelegate.setOrderInfoUI(orderInfoModel);
                        } else {
                            super.onNext(orderInfoModel);
                        }
                    }
                });
    }


    /**
     * 此时用到的memberId是订单所属人的id
     * 获取外带订单信息
     */
    public void getTakeOutOrderInfo() {
        JsonApiWrapper.getApiService().getOrderInfo(ApiConstant.MASTER_ID, DataUtils.getKey(), ApiConstant.BRANCH_ID, memberId, mOrderId)
                .compose(new DefaultTransformer<SanFangBaseModel<OrderInfoModel>>())
                .subscribe(new ProgressSubscriber<SanFangBaseModel<OrderInfoModel>>(this, true) {
                    @Override
                    public void onNext(SanFangBaseModel<OrderInfoModel> orderInfoModel) {
                        if (orderInfoModel.Code == NetCode.HTTP_200 && orderInfoModel.Data != null) {
                            viewDelegate.setOrderInfoUI(orderInfoModel);
                        } else {
                            super.onNext(orderInfoModel);
                        }
                    }
                });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_pay_confirm://确认支付
                if (viewDelegate.mNeedAmount > 0) {
                    pay();
                } else {
                    ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPayAmountIllegal));
                }
                break;
        }
    }

    /**
     * 判断是否设置支付密码
     */
    public void isSetPayPwd() {
        JsonApiWrapper.getApiService().userInfo(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<UserInfoModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<UserInfoModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<UserInfoModel>> listCompanyBaseModel) {
                        if (listCompanyBaseModel.code == 200 && listCompanyBaseModel.data != null && listCompanyBaseModel.data.size() > 0) {
                            if (listCompanyBaseModel.data.get(0).pay_pwd == 1) {
                                showDialog();
                            } else {
                                mDialogComment = new DialogComment(CodeUtils.getIdString(R.string.dialog_setPayPwd), new DialogComment.DialogCommentInterfaca() {
                                    @Override
                                    public void onConfirmListener() {
                                        SetPayPwdStepOneActivity.open(PayActivity.this, CodeUtils.getIdString(R.string.string_setPayPwd));
                                    }
                                });
                                mDialogComment.show(getSupportFragmentManager(), "TAG");
                            }
                        } else {
                            super.onNext(listCompanyBaseModel);
                        }

                    }
                });
    }

    /**
     * 先判断支付方式
     */
    public void pay() {
        switch (viewDelegate.getPayWay()) {
            case CodeConstant.PAY_WALLET://钱包支付 先判断是否设置支付密码
                isSetPayPwd();
                break;
            case CodeConstant.PAY_WECHART://微信支付
                ToastUtils.showToast(CodeUtils.getIdString(R.string.pay_wechartNo));
//                wechartPay();
                break;
            case CodeConstant.PAY_ALIPAY://支付宝支付
                aliPayService();
                break;
            default:
                ToastUtils.showToast(CodeUtils.getIdString(R.string.string_modifyPayPwd));
                break;
        }
    }

    /**
     * 弹出输入支付密码的弹窗
     */
    public void showDialog() {
        mPayPwd = new DialogInoutPayPwd(viewDelegate.mNeedAmount, viewDelegate.mBalance, new DialogInoutPayPwd.OnInputFinishListener() {
            @Override
            public void onFinish(String result) {
                walletPay(result);
            }
        });
        mPayPwd.show(getSupportFragmentManager(), "PayActivity");
    }

    /**
     * 支付宝支付向服务器请求orderInfo
     */
    private void aliPayService() {
        Integer order_type = null;
        if (!TextUtils.equals(memberId, SpUtils.getMemberId())) {//如果两个值不同则是别人的账单
            order_type = 2;
        }
        JsonApiWrapper.getApiService().walletPay(SpUtils.getToken(), memberId, mOrderId, CodeConstant.PAY_ALIPAY,
                viewDelegate.mNeedAmount + "", null, order_type, SpUtils.getMemberId(), mDeskId)
                .compose(new DefaultTransformer<CompanyBaseModel<List<ResultStringModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<ResultStringModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<ResultStringModel>> companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200 && companyBaseModel.data != null && companyBaseModel.data.size() > 0) {//成功
                            String info = companyBaseModel.data.get(0).info;
                            aliPay(info);
                        } else {
                            super.onNext(companyBaseModel);
                        }

                    }
                });
    }

    /**
     * 唤醒支付宝支付
     *
     * @param orderInfo 订单信息
     */
    public void aliPay(final String orderInfo) {
        if (mAliPayUtils == null) {
            mAliPayUtils = new AliPayUtils(this, this);
        }
        mAliPayUtils.aliPay(orderInfo);
    }

    /**
     * 微信
     */
    private void wechartPay() {

    }

    /**
     * 此时用到的 memberId是订单所属人的id
     * 钱包
     */
    public void walletPay(String pwd) {
        Integer order_type = null;
        if (!TextUtils.equals(memberId, SpUtils.getMemberId())) {//如果两个值不同则是别人的账单
            order_type = 2;
        }
        String pwdMD5 = DataUtils.md5(DataUtils.md5(pwd + CodeConstant.SET_PAY_PWD_MD5));
        JsonApiWrapper.getApiService().walletPay(SpUtils.getToken(), memberId, mOrderId, CodeConstant.PAY_WALLET,
                viewDelegate.mNeedAmount + "", pwdMD5, order_type, SpUtils.getMemberId(), mDeskId)
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200) {//成功
                            next();
                        } else {
                            super.onNext(companyBaseModel);
                        }

                    }
                });
    }

    /**
     * 支付成功关闭页面
     */
    public void sendPaySuccess() {
        EventFinishActivity eventFinishActivity = new EventFinishActivity();
        eventFinishActivity.paySuccess = true;
        EventBus.getDefault().post(eventFinishActivity);
        finish();
    }

    /**
     * 获取支付宝支付结果
     */
    public void getAliPayServiceReturn() {
        JsonApiWrapper.getApiService().aliPayReturn(SpUtils.getToken(), memberId, mOrderId)
                .compose(new DefaultTransformer<CompanyBaseModel<AliPayReturnModel>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<AliPayReturnModel>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<AliPayReturnModel> companyBaseModel) {
                        if (companyBaseModel.code == 200 && companyBaseModel.data != null) {
                            if (TextUtils.equals(companyBaseModel.data.trade_status, CodeConstant.ALIPAY_RETURN_STATUS)) {
                                next();
                            } else {
                                ToastUtils.showToast("支付宝返回错误");
                            }
                        } else {
                            super.onNext(companyBaseModel);
                        }
                    }
                });
    }

    /**
     * 支付成功下一步操作
     */
    public void next() {
        ToastUtils.showToast("支付成功！");
        sendPaySuccess();
        PaymentResultActivity.open(PayActivity.this, viewDelegate.getPayWay(), viewDelegate.mNeedAmount, mOrderId, memberId);
    }

    /**
     * 支付宝支付成功
     */
    @Override
    public void onSucessListener() {
        getAliPayServiceReturn();
    }

    @Override
    public void onFaliListener() {
        getAliPayServiceReturn();
    }
}
